package com.qinghe.pro.shiro;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.qinghe.pro.entity.main.Permission;
import com.qinghe.pro.entity.main.Role;
import com.qinghe.pro.entity.main.RolePermission;
import com.qinghe.pro.entity.main.User;
import com.qinghe.pro.entity.main.UserRole;
import com.qinghe.pro.service.main.RoleService;
import com.qinghe.pro.service.main.UserService;

/**
 * 
 * 项目名称：feing
 * 类名称：ShiroDbRealm
 * 类描述：登录、权限过滤
 * 创建人：longfei
 * 创建时间：2014-2-19 下午1:27:57
 * @version 
 * 
 */
public class ShiroDbRealm extends AuthorizingRealm {
	private static final Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
	
	// 是否启用超级管理员
	protected boolean activeRoot = false;
	
	// 是否使用验证码
	protected boolean useCaptcha = false;
	
	@Autowired
	protected UserService userService;
	
	@Autowired
	protected RoleService roleService;
	
	/**
	 * 认证回调函数,登录时调用,对认证进行缓存处理
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		if (useCaptcha) {
			CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
			String parm = token.getCaptcha();
			
			if (!PatchcaServlet.validate(SecurityUtils.getSubject().getSession().getId().toString(), parm.toLowerCase())) {// 忽略大小写。
				throw new IncorrectCaptchaException("验证码错误！");
			}
		}
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = userService.findByUsername(token.getUsername());
		if (user != null) {
			if (user.getStatus() == User.STATUS_DISABLED) {
				throw new DisabledAccountException();
			}
			
			ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername());
			
			// 这里可以缓存认证
			return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), getName());
		} else {
			return null;
		}
	}
	
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Collection<?> collection = principals.fromRealm(getName());
		if (collection == null || collection.isEmpty()) {
			return null;
		}

		ShiroUser shiroUser = (ShiroUser) collection.iterator().next();
		// 设置、更新User
		if (shiroUser.getUser() == null) {
			shiroUser.setUser(userService.findById(shiroUser.getId()));
		}
		return newAuthorizationInfo(shiroUser);
	}
	
	private SimpleAuthorizationInfo newAuthorizationInfo(ShiroUser shiroUser) {
		Collection<String> hasPermissions = null;
		Collection<String> hasRoles = null;
		
		// 是否启用超级管理员 && id==1为超级管理员，构造所有权限
		if (activeRoot && shiroUser.getId() == 1) {
			hasRoles = new HashSet<String>();
			List<Role> roles = roleService.findAll();
			
			for (Role role : roles) {
				hasRoles.add(role.getName());
			}
			
			hasPermissions = new HashSet<String>();
			hasPermissions.add("*");
			
			if (logger.isDebugEnabled()) {
				logger.debug("使用了" + shiroUser.getLoginName() + "的超级管理员权限:" + "。At " + new Date());
				logger.debug(shiroUser.getLoginName() + "拥有的角色:" + hasRoles);
				logger.debug(shiroUser.getLoginName() + "拥有的权限:" + hasPermissions);
			}
		} else {
			List<UserRole> userRoles = userService.findById(shiroUser.getId()).getUserRoles();
			
			Set<Role> roles = new HashSet<Role>();
			for (UserRole userRole : userRoles) {
				roles.add(userRole.getRole());
			}
			
			hasRoles = makeRoles(roles, shiroUser);
			hasPermissions = makePermissions(roles, shiroUser);
		}
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(hasRoles);
		info.addStringPermissions(hasPermissions);
		
		return info;
	}
	
	/**
	 * 组装角色权限
	 * @param shiroUser
	 * @return
	 */
	private Collection<String> makeRoles(Collection<Role> roles, ShiroUser shiroUser) {
		Collection<String> hasRoles = new HashSet<String>();
		for (Role role : roles) {
			hasRoles.add(role.getName());
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug(shiroUser.getLoginName() + "拥有的角色:" + hasRoles);
		}
		return hasRoles;
	}
	
	/**
	 * 组装资源操作权限
	 * @param shiroUser
	 * @return
	 */
	private Collection<String> makePermissions(Collection<Role> roles, ShiroUser shiroUser) {
		Collection<String> stringPermissions = new ArrayList<String>();
		for (Role role : roles) {
			List<RolePermission> rolePermissions = role.getRolePermissions();
			for (RolePermission rolePermission : rolePermissions) {
				Permission permission = rolePermission.getPermission();
				
				String resource = permission.getModule().getSn();
				String operate = permission.getSn();
				
				StringBuilder builder = new StringBuilder();
				builder.append(resource + ":" + operate);
				
				stringPermissions.add(builder.toString());
			}
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug(shiroUser.getLoginName() + "拥有的权限:" + stringPermissions);
		}
		return stringPermissions;
	}
	
	/**
	 * 覆盖父类方法，设置AuthorizationCacheKey为ShiroUser的loginName，这样才能顺利删除shiro中的缓存。
	 * 因为shiro默认的AuthorizationCacheKey为PrincipalCollection的对象。
	 * @see org.apache.shiro.realm.AuthorizingRealm#getAuthorizationCacheKey(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		return shiroUser.getLoginName();
	}
	
	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String loginName) {
		ShiroUser shiroUser = new ShiroUser(loginName);
		
		SimplePrincipalCollection principals = new SimplePrincipalCollection(shiroUser, getName());
		clearCachedAuthorizationInfo(principals);
	}
	
	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
	
	/**  
	 * 设置 isActiveRoot 的值  
	 * @param isActiveRoot
	 */
	public void setActiveRoot(boolean activeRoot) {
		this.activeRoot = activeRoot;
	}
	
	/**  
	 * 设置 useCaptcha 的值  
	 * @param useCaptcha
	 */
	public void setUseCaptcha(boolean useCaptcha) {
		this.useCaptcha = useCaptcha;
	}

}
